<?php

namespace App\Http\Controllers\Admin;

use App\Services\Admin\AuthService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthController extends AdminBaseController
{
    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

    public function login(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $credentials =  $request->only('username', 'password');

        $data = $this->authService->login($credentials);

        return $this->success($data);
    }

    public function logout()
    {
        if (auth('admin')->check()) {
            $this->authService->logout();
        }

        return $this->success(['message' => '退出成功']);
    }

    public function refresh()
    {
        return $this->success($this->authService->refresh());
    }

    /**
     * 获取用户信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return $this->success($this->authService->me());
    }

    public function changePassword(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'old_password' => 'required|string|min:6',
            'new_password' => 'required|string|min:6|confirmed',
            'new_password_confirmation' => 'required|string|min:6',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), 422);
        }

        $adminId = $request->user()->id;
        $result = $this->authService->changePassword($adminId, $request->only(['old_password', 'new_password']));

        return $this->success($result);
    }
}
